//
//  WSComponentsViewController.swift
//  DIYComputer
//
//  Created by 王广威 on 2016/9/22.
//  Copyright © 2016年 forever. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class WSComponentsViewController: WSTableViewController {
	
	var componentsModel : WSDIYComponentsModel?
	
	
    override func viewDidLoad() {
        super.viewDidLoad()
		self.requestParameter.updateValue("IphoneDiy_Detail", forKey: "c")
		self.title = "装机配置单"
		
		// Do any additional setup after loading the view.
		self.getComponentsData()
		
//		self.tableView.rowHeight = 72
		self.tableView.allowsSelection = false
		self.tableView.registerNibOf(WSComponentsCell)
		self.tableView.registerHeaderFooterNibOf(WSTotalFooterView)
    }
	
	func getComponentsData() {
		
		Alamofire.request(.GET, "http://lib3.wap.zol.com.cn/index.php", parameters: requestParameter, encoding: ParameterEncoding.URL, headers: nil).responseJSON { (response) in
			switch response.result
			{
			case .Success:
				let jsonData = JSON(response.result.value!)
				
				let resultArr = jsonData["newDetail"].rawValue
				let componentsJson = jsonData["main"].rawValue
				
				if let models = NSArray.modelArrayWithClass(WSComponentDetailModel.self, json: resultArr) {
					self.componentsModel = WSDIYComponentsModel.modelWithJSON(componentsJson)
					self.cellModels = models
					self.tableView.reloadData()
				}
				
				break
			case .Failure:
				
				break
			}
		}
	}

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
	
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


extension WSComponentsViewController {
	
	override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return self.cellModels.count
	}
	
	func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
		return self.componentsModel == nil ? 0 : 72
	}
	
	func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
		let footer : WSTotalFooterView = tableView.dequeueReusableHeaderFooter()
		
		if self.componentsModel == nil {
			return nil
		}
		
		footer.configureWithComponents(componentsModel!)
		return footer
	}
	
	override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
		let cell : WSComponentsCell = tableView.dequeueReusableCell()
		
		let componentDetail = self.cellModels[indexPath.row] as! WSComponentDetailModel
		cell.configureWithComponentDetail(componentDetail)
		
		return cell
	}
}

